package com.share.hope.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.share.hope.entity.RecordInfo;
import com.share.hope.entity.UserInfo;
import com.share.hope.service.RecordInfoService;
import com.share.hope.service.UserInfoService;
import com.share.hope.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class RecordInfoScheduled {

    private final UserInfoService userInfoService;

    private final RecordInfoService recordInfoService;

    /**
     * 每天23:59:59把今天没有打卡的用户连续签到日期改为0
     */
//    @Scheduled(cron = "0/2 * * * * ?")
    @Scheduled(cron = "59 59 23 * * ?")
    public void setAbsenteesPunchStreakToZero() {
        String today = DateUtil.getToday();
        QueryWrapper<RecordInfo> recordInfoQueryWrapper = new QueryWrapper<>();
        recordInfoQueryWrapper.eq("punch_time", today);
        List<RecordInfo> recordInfos = recordInfoService.list(recordInfoQueryWrapper);
        // 今日打卡的用户id
        List<Long> recordIds = recordInfos.stream().map(RecordInfo::getUserId).collect(Collectors.toList());
        // 全量用户id
        List<Long> ids = userInfoService.list().stream().map(UserInfo::getId).collect(Collectors.toList());
        // 去除打卡的用户 剩余未打卡的用户并把连续打卡日改为0
        ids.removeAll(recordIds);

        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids);
        updateWrapper.set("punch_streak", 0);
        log.info("[setAbsenteesPunchStreakToZero] {} unchecked users is: {}", today, ids);
        userInfoService.update(updateWrapper);
    }

}
